<!-- 任务委托申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="handlerId" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.handlerId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.handlerId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="handlerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.handlerDeptId"
            :departName="model.handlerDeptId_dictText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.handlerDeptId_dictText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-distribution-input
            :projectStatus="'2'"
						:proDisabled="true"
						:isContractManager="true"
            v-model="model.projectId"
						objectField="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @input="onChangeProjectName"
          ></h-select-project-distribution-input>
        </u-form-item>
        <u-form-item label="项目编号" prop="finalNo">
          <u--input disabled placeholder="请输入项目编号" v-model="model.finalNo"></u--input>
        </u-form-item>
        <u-form-item label="经营团队" prop="teamName">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.teamName"
            objectField="model.teamName"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="1"
          />
        </u-form-item>
        <!-- <u-form-item
				label="经营公司"
				prop="businessCompanyId"
				:borderBottom="false"
				>
				<h-select-company-input
					disabled
					style="width: 100%"
					v-model="model.businessCompanyId"
					border="surround"
					placeholder="请选择经营公司"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{color: '#B2B2B2'}"
					objectField = 'managerTrusteeForm.gsdaId'
				></h-select-company-input>
              </u-form-item> -->

        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            disabled
            v-model="model.undertaker"
            style="width: 100%"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="立项日期" prop="projectEstablishDate">
          <h-time-select
            disabled
            mode="datetime"
            v-model="model.projectEstablishDate"
            placeholder="请选择立项日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="签订单位" prop="signUnit">
          <h-select-company-input-popup
            disabled
            style="width: 100%"
            v-model="model.signUnit"
            commercialType="1"
            placeholder="请选择公司"
            border="surround"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="year">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.year"
            objectField="model.year"
            placeholder="请选择业绩归属年度"
            border="surround"
            dictName="yjgsnd"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="业主单位" prop="ownerUnit">
          <h-select-customer-input-popup
            disabled
            style="width: 100%"
            v-model="model.ownerUnit"
            objectField="model.ownerUnit"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
          ></h-select-customer-input-popup>
        </u-form-item>
        <u-form-item label="联系人" prop="contacts">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.contacts"
            objectField="model.contacts"
            placeholder="请选择联系人"
            border="surround"
            :dictName="cust_lxr"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="联系方式" prop="contactTel">
          <u--input disabled placeholder="请输入联系方式" v-model="model.contactTel"></u--input>
        </u-form-item>
        <u-form-item label="项目所在地址" prop="areaCode" :borderBottom="false">
          <h-select-address-input
            disabled
            style="width: 100%"
            v-model="model.areaCode"
            placeholder="请选择项目地址"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-address-input>
        </u-form-item>
        <u-form-item label="项目详细地址" prop="projectAddress" :borderBottom="false">
          <u--input disabled placeholder="请输入项目详细地址" v-model="model.projectAddress"></u--input>
        </u-form-item>
        <u-form-item label="项目来源" prop="projectSource">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.projectSource"
            objectField="model.projectSource"
            placeholder="请选择项目来源"
            border="surround"
            dictName="xmly_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="预计合同额(元)" prop="estimatedContractAmount">
          <u--input
            disabled
            type="number"
            
            placeholder="请输入预计合同额"
            v-model="model.estimatedContractAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="预计合同额大写" prop="estimatedContractcapitalChineseAmount">
          <u--input disabled placeholder="请输入预计合同额大写" v-model="model.estimatedContractcapitalChineseAmount"></u--input>
        </u-form-item>
        <u-form-item label="立项事由及说明" prop="establishReason">
          <u--textarea
            disabled
            maxlength="500"
            confirm-type="send"
            v-model="model.establishReason"
            placeholder="请输入立项事由及说明"
          ></u--textarea>
        </u-form-item>
        <view>
          <view class="basic-title basic-border">项目附件</view>
          <view class="py-1 space-y-1" style="width: 100%">
            <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
            <file-list v-if="model.attachment" v-model="model.attachment"></file-list>
						<view v-else>
							<u-empty
								mode="data"
								text="暂无项目附件"
								icon="/static/empty/data.png"
							></u-empty>
						</view>
          </view>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">任务信息</view>
        <u-form-item label="任务编号" prop="taskId" required>
          <h-select-task-file-input-popup
            :projectId="model.projectId"
            :api="erpOmcProjectTaskFinalList"
            v-model="model.taskId"
            class="w-100"
            :disabled="!model.projectId"
            :placeholder="model.projectId ? '请选择任务编号' : '请先选择项目'"
            searchPlaceholder="请输入任务编号"
            border="surround"
            label="billNo"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @realChange="onTaskIdInput"
            :customParams="{
              changeStatus: '!changing',
              distributionType: 'waiting',
            }"
            @select="model.taskDescription = $event.taskDescription"
          ></h-select-task-file-input-popup>
        </u-form-item>
        <u-form-item label="业务分类" prop="categoryName">
          <u--input disabled placeholder="请输入业务分类" v-model="model.categoryName"></u--input>
        </u-form-item>
        <u-form-item label="合同占比(%)" prop="contractRate">
          <u--input disabled type="number"  placeholder="请输入合同占比" v-model="model.contractRate"></u--input>
        </u-form-item>
        <u-form-item label="合同分配额(元)" prop="contractAmount">
          <u--input disabled type="number"  placeholder="请输入合同分配额" v-model="model.contractAmount"></u--input>
        </u-form-item>
        <u-form-item label="切割合同额(元)" prop="cutContractAmount">
          <u--input disabled type="number"  placeholder="请输入切割合同额" v-model="model.cutContractAmount"></u--input>
        </u-form-item>
        <u-form-item label="生产团队" prop="productTeam">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.productTeam"
            objectField="model.productTeam"
            placeholder="请选择生产团队"
            border="surround"
						suffixIcon="arrow-down-fill"
						            :suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="2"
          />
        </u-form-item>
        <!-- <u-form-item
          label="生产公司"
          prop="productCompanyId"
          :borderBottom="false"
        >
          <h-select-company-input
            disabled
            style="width: 100%"
            v-model="model.productCompanyId"
            border="surround"
            placeholder="请选择生产公司"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{color: '#B2B2B2'}"
          ></h-select-company-input>
          </u-form-item> -->
        <u-form-item label="任务类型" prop="taskType" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.taskType"
            objectField="model.taskType"
            placeholder="请选择任务类型"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="task_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="实施部门" prop="executeDepart">
          <h-select-depart-input
            v-model="model.executeDepart"
            :departName="model.executeDepartText"
            placeholder="请选择实施部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.executeDepartText"
            @detail="onExecuteDepartInput"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="部门负责人" prop="minister">
					<h-select-person-input
					  style="width: 100%"
					  v-model="model.minister"
					  placeholder="请选择部门负责人"
					  border="surround"
					  isMulti
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  objectField="model.minister"
					></h-select-person-input>
        </u-form-item>
        <u-form-item label="项目负责人" prop="projectLeading">
          <h-select-person-input-popup
            v-model="model.projectLeading"
            style="width: 100%"
            placeholder="请选择项目负责人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>

        <!-- 当任务类型为环评咨询，水保咨询时，展示本项 -->
        <template v-if="model.taskType == 1 || model.taskType == 4">
          <u-form-item label="审核工程师" prop="approvalEngineer" v-if="model.taskType == 1">
            <h-select-person-input-popup
              v-model="model.approvalEngineer"
              style="width: 100%"
              placeholder="请选择审核工程师"
              searchPlaceholder="请输入"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-select-person-input-popup>
          </u-form-item>
          <u-form-item label="审批级别" prop="approvalLevel">
            <h-select-input-tag
              class="w-100"
              v-model="model.approvalLevel"
              objectField="model.approvalLevel"
              placeholder="请选择审批级别"
              border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
              dictName="approval_level"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="审批系数" prop="approvalCoefficient">
						<h-number-input placeholder="请输入审批系数" v-model="model.approvalCoefficient" :min="0"></h-number-input>
          </u-form-item>
          <u-form-item label="行业类别" prop="industryCategory">
            <h-select-input-tag
              class="w-100"
              v-model="model.industryCategory"
              objectField="model.industryCategory"
              placeholder="请选择行业类别"
              border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
              dictName="industry_category"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="行业系数" prop="industryCoefficient">
						<h-number-input placeholder="请输入行业系数" v-model="model.industryCoefficient" :min="0"></h-number-input>
          </u-form-item>
          <u-form-item label="复杂程度" prop="complexity">
            <h-select-input-tag
              class="w-100"
              v-model="model.complexity"
              objectField="model.complexity"
              placeholder="请选择复杂程度"
              border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
              dictName="industry_coefficient"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="复杂系数" prop="complexCoefficient">
						<h-number-input placeholder="请输入复杂系数" v-model="model.complexCoefficient" :min="0"></h-number-input>
          </u-form-item>
        </template>

        <!-- 当任务类型为检验检测时，展示本项 -->
        <template v-if="model.taskType == 2">
          <u-form-item label="是否出具报告" prop="isOutReport">
            <h-select-input-tag
              class="w-100"
              v-model="model.isOutReport"
              objectField="model.isOutReport"
              placeholder="请选择是否出具报告"
              border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
              dictName="YES_OR_NO"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="费用核算方式" prop="expenseAccountingMethod">
            <h-select-input-tag
              class="w-100"
              v-model="model.expenseAccountingMethod"
              objectField="model.expenseAccountingMethod"
              placeholder="请选择费用核算方式"
              border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
              dictName="expense_accounting_method"
            ></h-select-input-tag>
          </u-form-item>
        </template>
        <u-form-item label="说明" prop="instruction">
          <u--textarea maxlength="500" confirm-type="send" v-model="model.instruction" placeholder="请输入说明"></u--textarea>
        </u-form-item>
        <view class="basic-title basic-border">任务附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.taskFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.taskFile" v-model="model.taskFile" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目成员</view>
        <u-collapse v-if="formData && formData.length">
          <u-collapse-item :title="item.projectMember_dictText" v-for="(item, index) in formData" :key="index">
            <FormInfo :item="item" :index="index" @edit="handleEditForm" :disabled="true" @remove="handleRemoveForm" @copy="handleCopyForm" />
          </u-collapse-item>
        </u-collapse>
				<view v-else>
					<u-empty
						mode="data"
						icon="/static/empty/data.png"
					></u-empty>
				</view>
        <u-popup class="form-popup" mode="right" :show="showFormModal" @close="closeFormModal" @open="openFormModal">
          <MemberForm ref="dataForm" :index="index" @submit="handleFormSubmit" @close="showFormModal = false" :model="model" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">项目预算</view>
        <u-form-item label="预算总工时(人小时)" prop="expectWorkTime">
          <u--input type="number" disabled  placeholder="请输入预算工时(人小时)" v-model="model.expectWorkTime"></u--input>
        </u-form-item>
				<u-form-item label="生产总绩效(元)" prop="totalProductPerformance">
          <u--input type="number" disabled  placeholder="请输入生产总绩效" v-model="model.totalProductPerformance"></u--input>
        </u-form-item>
        <u-form-item label="人工成本(元)" prop="workCost">
          <u--input type="number" disabled  placeholder="请输入人工成本" v-model="model.workCost"></u--input>
        </u-form-item>
        <u-form-item label="委外费(元)" prop="outsourcingFee">
          <u--input type="number" disabled  placeholder="请输入委外费" v-model="model.outsourcingFee"></u--input>
        </u-form-item>
        <u-form-item label="差旅费(元)" prop="travelFee">
          <u--input type="number" disabled  placeholder="请输入差旅费" v-model="model.travelFee"></u--input>
        </u-form-item>
        <u-form-item label="专家评审费(元)" prop="professionReviewFee">
          <u--input type="number" disabled  placeholder="请输入专家评审费" v-model="model.professionReviewFee"></u--input>
        </u-form-item>
        <u-form-item label="其他成本(元)" prop="otherCost">
          <u--input type="number" disabled  placeholder="请输入其他成本" v-model="model.otherCost"></u--input>
        </u-form-item>
        <u-form-item label="项目预算合计(元)" disabled prop="outsourcingFee">
          <u--input
            disabled
            type="number"
            placeholder="人工总成本+委外费+差旅费+专家评审费+其他成本"
            v-model="model.totalProjectBudget"
          ></u--input>
        </u-form-item>
				<template v-if="model.categoryName">
					<view v-if="isProjectInformation">
					  <view class="basic-title basic-border">项目预算表</view>
					  <view class="py-1 space-y-1" style="width: 100%">
					    <file-list v-if="model.projectBudgetFile" v-model="model.projectBudgetFile"></file-list>
							<view v-else>
								<u-empty
									mode="data"
									text="暂无项目预算表"
									icon="/static/empty/data.png"
								></u-empty>
							</view>
					  </view>
					</view>
					<view v-else>
					  <view class="basic-title basic-border">生产绩效表</view>
					  <view class="py-1 space-y-1" style="width: 100%">
					    <file-list v-if="model.productBudgetFile" v-model="model.productBudgetFile"></file-list>
							<view v-else>
								<u-empty
									mode="data"
									text="暂无生产绩效表"
									icon="/static/empty/data.png"
								></u-empty>
							</view>
					  </view>
					</view>
				</template>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">任务进度</view>
        <u-form-item label="进度模板" prop="templateId" :borderBottom="false">
          <!-- disabled -->
          <h-select-process-template-input
            disabled
            style="width: 100%"
            v-model="model.templateId"
            objectField="model.templateId"
            placeholder="请选择进度模板"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @input="getTemplateList"
          ></h-select-process-template-input>
        </u-form-item>
				<u-form-item label="允许添加子节点" prop="isAddChildNode">
				  <h-select-input-tag
						disabled
				    class="w-100"
				    v-model="model.isAddChildNode"
				    objectField="model.isAddChildNode"
				    placeholder="请选择允许添加子节点"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="yes_no"
				  ></h-select-input-tag>
				</u-form-item>
				<u-form-item label="收入确认方式" prop="confirmIncomeMethod">
				  <h-select-input-tag
				    class="w-100"
						disabled
				    v-model="model.confirmIncomeMethod"
				    objectField="model.confirmIncomeMethod"
				    placeholder="请选择收入确认方式"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="confirm_income_method"
				  ></h-select-input-tag>
				</u-form-item>
        <u-collapse v-if="templateDataList && templateDataList.length">
          <u-collapse-item :title="item.nodeName" v-for="(item, index) in templateDataList" :key="index">
            <u-form labelWidth="auto" disabled>
              <u-form-item :label="key" v-for="(child, key) in taskProgressFields" :key="key">
                {{ item[child] }}
              </u-form-item>
            </u-form>
          </u-collapse-item>
        </u-collapse>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">款项进度</view>
        <u-collapse v-if="progressNodeVoList && progressNodeVoList.length" ref="progressNodeVocollapse">
          <u-collapse-item :title="item.nodeName" v-for="(item, index) in progressNodeVoList" :key="index">
            <PriceFormInfo
              disabled
							:isShow = "false"
              :item="item"
              :index="index"
              :progressVoList="templateDataList"
              @edit="handleEditPriceForm"
              @remove="handleRemovePriceForm"
              @copy="handleCopyPriceForm"
            />
          </u-collapse-item>
        </u-collapse>
				<view v-else>
					<u-empty
						mode="data"
						text="合同未签订，暂无数据"
						icon="/static/empty/data.png"
					></u-empty>
				</view>
        <u-popup class="form-popup" mode="right" :show="showPriceFormModal" @close="closePriceFormModal" @open="openPriceFormModal">
          <PriceForm
            :progressVoList="templateDataList"
            ref="priceForm"
            :index="index"
            @submit="handlePriceFormSubmit"
            @close="showPriceFormModal = false"
          />
        </u-popup>
        <!-- <u-form-item label="履约保证金(元)" prop="bail">
          <u--input type="number" disabled  placeholder="请输入履约保证金" v-model="model.bail"></u--input>
        </u-form-item>
        <u-form-item label="款项节点说明" prop="paymentDesc" v-if="Number(model.bail)">
          <u--textarea maxlength="500" confirm-type="send" v-model="model.paymentDesc" placeholder="请输入款项节点说明"></u--textarea>
        </u-form-item>
        <template v-if="Number(model.bail)">
          <u-form-item label="是否应收" prop="isCollectionPayment">
            <h-select-input-tag
              class="w-100"
              v-model="model.isCollectionPayment"
              objectField="model.isCollectionPayment"
              placeholder="请选择是否应收"
              border="surround"
              dictName="YES_OR_NO"
            ></h-select-input-tag>
          </u-form-item>
        </template>
        <template v-if="model.isCollectionPayment == 1">
          <u-form-item label="预计应收日期" prop="collectionDate">
            <h-time-select
              mode="datetime"
              v-model="model.collectionDate"
              placeholder="请选择应收日期"
              border="surround"
              suffixIcon="calendar-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-time-select>
          </u-form-item>
        </template> -->
      </view>
      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
    </u-form>
    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { erpProgressTemplateDtList, queryDistributionProjectList, erpOmcProjectTaskFinalList, queryUsersByUsernames } from '@/api/index'
import {
  gainBillNo,
  add,
  info,
  edit,
  queryPageList,
  queryPaymentNodeListByMainId,
  erpOmcProjectQueryById,
} from '@/api/project/ErpProgressTaskDistributionForm'
import http from '@/utils/request/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import MemberForm from './components/MemberForm.vue'
import FormInfo from './components/MemberFormInfo.vue'
import PriceForm from './components/PriceForm.vue'
import PriceFormInfo from './components/PriceFormInfo.vue'
import Decimal from 'decimal.js'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpOmcTaskDistributionForm',
  components: {
    fileList,
    MemberForm,
    FormInfo,
    PriceForm,
    PriceFormInfo,
    ProcessNodeConfiguration,
  },
  data() {
    return {
			isEditProgressNode: false,
      isSubmit: false,
      flowCode: 'dev_erp_omc_task_distribution_001',
      flowChangeCode: 'dev_erp_omc_task_distribution_002',
      beanName: 'erpOmcTaskDistributionServiceImpl',
      formUrl: '/erp/omc/taskdistribution/modules/ErpOmcTaskDistributionForm',
      formChangeUrl: '/erp/omc/taskdistribution/modules/taskchange/ErpProgressTaskChangeListForm',
      formUrlMobile: '/pages/synergy/ErpOmcTaskDistributionForm',
      formChangeUrlMobile: '/pages/synergy/ErpOmcTaskChangeForm',
      processId: '1557666877169283074',
      queryDistributionProjectList,
      erpOmcProjectTaskFinalList,
      taskProgressFields: {
        节点名称: 'nodeName',
        节点进度: 'nodeProgress',
				'收入确认节点': 'isConfirmIncomeNode_dictText'
        // 完成状态: 'taskCompleteStatus_dictText',
        // 完成时间: 'completeTime',
      },
      templateDataList: [],
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0',
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      showPriceFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      formData: [],
      progressNodeVoList: [],
      model: {
        applyType: 1,
        billNo: '',
        createTime: '',
        handlerId: '',
        handlerDeptId: '',
        projectId: '',
        finalNo: '',
        teamName: '',
        undertaker: '',
        businessCompanyId:'',
        projectEstablishDate: '',
        signUnit: '',
        year: '',
        ownerUnit: '',
        contacts: '',
        contactTel: '',
        areaCode: '',
        projectAddress: '',
        projectSource: '',
        estimatedContractAmount: '',
        estimatedContractcapitalChineseAmount: '',
        establishReason: '',
        taskId: '',
        categoryName: '',
        categoryCode: '',
        contractRate: '',
        contractAmount: '',
        cutContractAmount:'',
        productTeam: '',
        productCompanyId:'',
        taskType: '3',
        executeDepart: '',
        minister: '',
        projectLeading: '',
        taskFile: null,
        templateId: '',
				isAddChildNode: '',
				confirmIncomeMethod: '',
        purchaseFile: null,
      },
      rules: {
        billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
        handlerId: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
        createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        handlerDeptId: [{ required: true, message: '请选择部门!', trigger: ['blur', 'change'] }],
        projectId: [{ required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }],
        taskType: [{ required: true, message: '请选择任务类型!' }],
        taskId: [{ required: true, message: '请选择任务编号!' }],
      },
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
		// 判断是否为工程运维或者数字信息的业务分类
		isProjectInformation() {
			// 判断categoryName是否含有工程运维或者数字信息
			if (this.model.categoryName && (this.model.categoryName.indexOf('工程运维') !== -1 || this.model.categoryName.indexOf('数字信息') !== -1)) {
				return true
			} else {
				return false
			}
		}
  },
  methods: {
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
    getFieldsValue(key, value) {
      if (key === '是否关联任务节点' || key === '是否关联进度') {
        return value === '1' ? '是' : '否'
      }
      return value
    },
    // 选择项目名称
    async onChangeProjectName(event) {
      if (!event) {
        this.$set(this.model, 'projectName', '') // 项目名称
        this.$set(this.model, 'bail', '') // 保证金
        this.$set(this.model, 'finalNo', '') // 项目编号
        this.$set(this.model, 'teamName', '') // 经营团队
        this.$set(this.model, 'businessCompanyId', '') // 经营公司
        this.$set(this.model, 'undertaker', '') // 项目承接人
        this.$set(this.model, 'projectEstablishDate', '') // 立项日期
        this.$set(this.model, 'signUnit', '') // 签订单位
        this.$set(this.model, 'year', '') // 业绩归属年度
        this.$set(this.model, 'ownerUnit', '') // 业主单位
        this.$set(this.model, 'contacts', '') // 联系人
        this.$set(this.model, 'contactTel', '') // 联系方式
        this.$set(this.model, 'areaCode', '') // 项目所在地址
        this.$set(this.model, 'projectAddress', '') // 项目所在详细地址
        this.$set(this.model, 'projectSource', '') // 项目来源
        this.$set(this.model, 'estimatedContractAmount', '') // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', '') // 预计合同额大写
        this.$set(this.model, 'establishReason', '') // 立项事由及说明
        this.$set(this.model, 'attachment', '') // 项目附件
        this.$set(this.model, 'categoryName', '') // 业务分类
        this.$set(this.model, 'categoryCode', '') // 业务分类
        this.$set(this.model, 'contractRate', '') // 合同占比(%)
        this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)
        this.$set(this.model, 'productTeam', '') // 生产团队
        this.$set(this.model, 'productCompanyId', '') // 生产公司
        this.$set(this.model, 'taskId', '') // 任务编号
        this.progressNodeVoList = [] // 清空款项进度
				this.clearTaskMsg()
        return false
      }
      
      this.getQueryByEntity(event.id) // 获取履约保证金
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
			this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
			this.$set(this.model, 'businessCompanyId', event.businessCompanyId) // 经营公司
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = "erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id='" + event.ownerUnit + "'"

      this.$set(this.model, 'categoryName', '') // 业务分类
      this.$set(this.model, 'categoryCode', '') // 业务分类
      this.$set(this.model, 'contractRate', '') // 合同占比(%)
      this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)

      this.$set(this.model, 'productTeam', '') // 生产团队
      this.$set(this.model, 'productCompanyId', '') // 生产公司
      this.$set(this.model, 'taskId', '') // 任务编号
    },
    // 选择任务编号
    onTaskIdInput(event) {

      if (!event) {
        this.$set(this.model, 'categoryName', '') // 业务分类
        this.$set(this.model, 'categoryCode', '') // 业务分类
        this.$set(this.model, 'contractRate', '') // 合同占比(%)
        this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
        this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)

        this.$set(this.model, 'productTeam', '') // 生产团队
        this.$set(this.model, 'productCompanyId', '') // 生产公司
				this.clearTaskMsg()
        this.$forceUpdate()
        return false
      }
      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)
      this.$set(this.model, 'cutContractAmount', event.cutContractAmount) // 切割合同额(元)
      this.$set(this.model, 'productCompanyId', event.productCompanyId) // 生产公司
      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队
			this.queryPaymentListByProjectId(event.id) // 获取款项进度列表
      this.$forceUpdate()
    },

    getQueryByEntity(id) {},

    // 获取款项进度列表
    queryPaymentListByProjectId(taskId) {
      // this.progressNodeVoList = []
      http.get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskPaymentList', { taskId }).then((res) => {
        if (res.success) {
          this.progressNodeVoList = res.result || []
					if (this.progressNodeVoList && this.progressNodeVoList.length) {
						this.$nextTick(() => {
							this.$refs.progressNodeVocollapse.init()
						})
					}
        }
      })
    },
    // 编辑获取款项进度列表
    queryPaymentNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.progressNodeVoList = []
      this.progressNodeVoLoading = true
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryPaymentNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
						this.isEditProgressNode = true // 用于判断是否是编辑的款项进度列表
            this.progressNodeVoList = res.result
          } else {
            this.queryPaymentListByProjectId(this.model.taskId) // 获取款项进度列表
          }
        })
        .finally(() => {
          this.progressNodeVoLoading = false
        })
    },
    // 编辑获取任务进度列表
    queryTaskNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.templateLoading = true
      this.templateDataList = []
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 选择实施部门
    onExecuteDepartInput(item) {
      if (!item[0].minister) {
        this.$set(this.model, 'minister', '')
        return false
      }
      // 赋值部门负责人
      queryUsersByUsernames( { usernames: item[0].minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map((value) => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()
        this.$set(this.model, 'minister', ids)
      })
    },

    // 选择进度模板
    getTemplateList(data) {
      erpProgressTemplateDtList({ mainId: data.id }).then((res) => {
				if (res.success) {
					// 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
					let isAddChildNode = data.isAddChildNode
					this.templateDataList = res.result.map((item, index) => {
						item.id = this.getRandomNum()
						if (index === res.result.length - 1) {
							item.isAddChildNode = '0'
						} else {
							item.isAddChildNode = isAddChildNode
						}
						return item
					})
				}
      })
    },

    // 获取唯一随机数
    getRandomNum() {
      let date = new Date().valueOf() // 获取时间戳
      let txt = '1234567890' // 生成的随机机器码
      let len = 19 // 机器码有多少位
      let pwd = '' // 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length)) // 循环机器码位数随机填充
      }
      return date + pwd
    },

    // initDictConfig() {
    //   initDictOptions('ywfx_type').then((res) => {
    //     if (res.success) {
    //       this.$set(this.dictOptions, 'ywfl', res.result)
    //     }
    //   })
    //   initDictOptions('erp_employee_file,name,id').then((res) => {
    //     if (res.success) {
    //       this.$set(this.dictOptions, 'projectMember', res.result)
    //     }
    //   })
    // },
    // 款项进度完善
    PerfectTaskChange(val) {
      this.progressNodeVoList.forEach((it, i) => {
        if (it.id === val.id) {
          this.progressNodeVoList.splice(i, 1, val)
        }
      })
    },
    // 获取任务进度
    getTaskNodeList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryTaskNodeList', { handlerType, id, projectId, taskId, isChild: '0' })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取款项进度
    getPaymentList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryPaymentList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.progressNodeVoList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 查看成员列表
    getMemberList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryMemberList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.formData = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取任务进度模板
    getTemplateId(id) {
      queryPageList({ id }).then((res) => {
        if (res.success) {
          var event = res.result.records[0]
          this.$set(this.model, 'templateId', event.templateId)
          this.$set(this.model, 'templateName', event.templateName)
        }
      })
    },
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
      this.$nextTick(() => {
        if (this.isReset) return
        const firstChar = key[0].toUpperCase()
        key = firstChar + key.slice(1)
        const oldData = this[`backUp${key}`]
        if (oldData && oldData !== this.model[key]) {
          this.confirmModal = true
          this.resetKey = `backUp${key}`
        } else {
          fn && fn(data)
        }
      })
    },
    projectChange() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
      this.foldTeamIdChange(v, num)
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', '')
        this.$set(this.model, 'foldWarehouse', '')
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', '')
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
    },
    handleChangeExportTeamId(v, num = 0) {
      if (v != this.exportTeamId) {
        this.exportTeamIdChange(v, num)
      }
      this.exportTeamId = this.model.exportTeamId
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', '')
            this.warehouse = null
          }
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, { ...data })
      } else {
        this.formData.push(data)
      }
      // this.initBuyerInfo()
    },
    // ----------不同子表分界线----------
    handleCopyPriceForm([item, index]) {
      this.progressNodeVoList.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditPriceForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showPriceFormModal = true
    },
    handleRemovePriceForm(item) {
      this.progressNodeVoList = this.progressNodeVoList.filter((i) => i !== item)
    },
    closePriceFormModal() {
      this.$refs.priceForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openPriceFormModal() {
      this.$refs.priceForm.basicForm = this.basicForm
    },
    addPriceForm() {
      this.index = null
      this.showPriceFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handlePriceFormSubmit([data, index]) {
      this.showPriceFormModal = false
      if (typeof index === 'number') {
        this.$set(this.progressNodeVoList, index, data)
      } else {
        this.progressNodeVoList.push(data)
      }
      // this.initBuyerInfo()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'RWFP', subSystemCode: '05' })
      this.model.billNo = res.result
      // this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.handlerId = this.userInfo.empId //当前登录人
      this.model.handlerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      for (const key in data) {
        this.$set(this.model, key, data[key])
      }
			// 因为暂存的原因需要做当没有项目名称的时候需要清除不能编辑的数据，但是因为后端数据缓存的原因，所以前端这里做下处理处理方式如下：
			// 1、对于没有选择项目名称，需要清除所有不可编辑的数据和子表数据
			// 2、对于没有选择任务编号，需要清除任务携带出来的数据
			// 对于1的处理
			if (!this.model.projectId) {
				this.clearProject()
				return false
			}
      this.cust_lxr = `erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=${data.ownerUnit}`
			if (this.model.projectId) {
				erpOmcProjectQueryById({ id: this.model.projectId }).then((res) => {
				  if (res.success) {
				    var event = res.result
				    this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
				  }
				})
			}
			// 对于2的处理
			if (!this.model.taskId) {
				this.clearTask()
				return false
			}
      this.queryPaymentNodeListByMainId(this.id) // 获取款项进度列表
      this.queryTaskNodeListByMainId(this.id) // 获取任务进度列表
      http.get('/api/erp/omc/task/erpOmcTaskDistributionDt/list', { mainId: this.id }).then((response) => {
        this.$set(this, 'formData', response.result || [])
      })
    },
		clearProject () {
			this.$set(this.model, 'projectName', '') // 项目名称
			this.$set(this.model, 'bail', '') // 保证金
			this.$set(this.model, 'finalNo', '') // 项目编号
			this.$set(this.model, 'teamName', '') // 经营团队
			this.$set(this.model, 'businessCompanyId', '') // 经营公司
			this.$set(this.model, 'undertaker', '') // 项目承接人
			this.$set(this.model, 'projectEstablishDate', '') // 立项日期
			this.$set(this.model, 'signUnit', '') // 签订单位
			this.$set(this.model, 'year', '') // 业绩归属年度
			this.$set(this.model, 'ownerUnit', '') // 业主单位
			this.$set(this.model, 'contacts', '') // 联系人
			this.$set(this.model, 'contactTel', '') // 联系方式
			this.$set(this.model, 'areaCode', '') // 项目所在地址
			this.$set(this.model, 'projectAddress', '') // 项目所在详细地址
			this.$set(this.model, 'projectSource', '') // 项目来源
			this.$set(this.model, 'estimatedContractAmount', '') // 预计合同额
			this.$set(this.model, 'estimatedContractcapitalChineseAmount', '') // 预计合同额大写
			this.$set(this.model, 'establishReason', '') // 立项事由及说明
			this.$set(this.model, 'attachment', '') // 项目附件

			this.$set(this.model, 'categoryName', '') // 业务分类
			this.$set(this.model, 'categoryCode', '') // 业务分类
			this.$set(this.model, 'contractRate', '') // 合同占比(%)
			this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
			this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)

			this.$set(this.model, 'productTeam', '') // 生产团队
			this.$set(this.model, 'productCompanyId', '') // 生产公司
			this.$set(this.model, 'taskId', '') // 任务编号
			this.progressNodeVoList = [] // 清空款项进度
			this.clearTaskMsg()
		},
		clearTask () {
			this.$set(this.model, 'categoryName', '') // 业务分类
			this.$set(this.model, 'categoryCode', '') // 业务分类
			this.$set(this.model, 'contractRate', '') // 合同占比(%)
			this.$set(this.model, 'contractAmount', '') // 合同分配额(元)
			this.$set(this.model, 'cutContractAmount', '') // 切割合同额(元)
			this.$set(this.model, 'productTeam', '') // 生产团队
			this.$set(this.model, 'productCompanyId', '') // 生产公司
			this.clearTaskMsg()
		},
		clearTaskMsg() {
		  const clearArr = [
		    'categoryName',
		    'categoryCode',
		    'contractRate',
		    'contractAmount',
        'cutContractAmount',
		    'productTeam',
        'productCompanyId',
		    'taskType',
		    'executeDepart',
		    'minister',
		    'projectLeading',
		    'isOutReport',
		    'approvalEngineer',
		    'approvalLevel',
		    'approvalCoefficient',
		    'industryCategory',
		    'industryCoefficient',
		    'complexity',
		    'complexCoefficient',
		    'expenseAccountingMethod',
		    'instruction',
		    'taskFile',
		    'distributionDtList',
		    'expectWorkTime',
				'totalProductPerformance',
		    'workCost',
		    'outsourcingFee',
		    'travelFee',
		    'professionReviewFee',
		    'otherCost',
		    'totalProjectBudget',
		    'templateId',
				'isAddChildNode',
				'confirmIncomeMethod',
		    'templateDataList',
		    'bail',
		    'paymentDesc',
		    'isCollectionPayment',
		    'collectionDate',
		    'templateName',
		  ]
		  clearArr.forEach((it) => {
		    this.$set(this.model, it, undefined)
		  })
		  this.templateDataList = []
		  this.progressNodeVoList = []
		},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        return Promise.resolve()
      })
    },
		async isBeginProcess() {
			return	http.get('/api/erp/omc/project/erpOmcProjectTask/checkTaskChangeById', { id: this.model.taskId }).then( res => {
				if (res.success) {
					return Promise.resolve()
				} else {
					this.$refs.uToast.show({
					  message: res.message,
					  type: 'default',
						complete () {
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
					this.isSubmit = false
					return Promise.reject(res.message)
				}
			})
		},
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
				var model = await {
          ...this.model,
          distributionDtList: this.formData,
          
          progressVoList: this.templateDataList,
        }
				if (this.isEditProgressNode) {
					model.progressNodeVoList = this.progressNodeVoList
				}
        const response = await url(model)
        if (response.success) {
          var that = this
					await this.isBeginProcess()
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
			var that = this
      // await this.validateForm()
			this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
				var model = await {
				  ...this.model,
				  distributionDtList: this.formData,
				  
				  progressVoList: this.templateDataList,
				}
				if (this.isEditProgressNode) {
					model.progressNodeVoList = this.progressNodeVoList
				}
        const response = await url(model)
        if (response.success) {
          this.$refs.uToast.show({
          	message: response.message,
          	type: 'default',
          	complete () {
          		that.isSubmit = false
          		if (getCurrentPages().length > 1) {
          			uni.navigateBack()
          		} else {
          			uni.reLaunch({
          				url: '/pages/home/home'
          			})
          		}
          		
          	}
          })
        }
      } finally {
        this.loading = false
      }
    },
  },
  watch: {
    'model.bail'(val) {
      if (!Number(val)) {
        this.$set(this.model, 'paymentDesc', null)
        this.$set(this.model, 'isCollectionPayment', null)
      }
    },
    formData(val) {
      if (!val) return

      function parse(num) {
        return Number(num) || 0
      }

      // 所有成员的预算工时之和
      this.model.expectWorkTime = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.expectWorkTime)).plus(total).toNumber())
      }, 0)
			// 所有成员的项目绩效之和
      this.model.totalProductPerformance = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.projectPerformance)).plus(total).toNumber())
      }, 0)

      // 所有成员的人工成本之和
      this.model.workCost = val.reduce((total, item) => {
        return parse(new Decimal(parse(item.laborCost)).plus(total).toNumber())
      }, 0)
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
